var orderId; //订单ID
var orders = eval('(' + readData(localStorage.order) + ')'); //获取订单对象
var payChannels = {};
document.addEventListener("plusready", getChanle, false);

//获取支付渠道
function getChanle() {
	if ("true" == localStorage.conformOrder) {
		document.getElementById("seeOrder").style.display = "block";
	}
	// 获取支付通道
	plus.payment.getChannels(function(channels) {
		var content = document.getElementById('dcontent');
		var info = document.getElementById("info");
		var txt = "支付通道信息：";
		for (var i in channels) {
			var channel = channels[i];
			payChannels[channel.id] = channel;
		}
		console.log(JSON.stringify(payChannels))
	}, function(e) {
		mui.toast("获取支付通道失败：" + e.message);
	});
}
//检查支付渠道
function checkServices(pc) {
	if (!pc.serviceReady) {
		var txt = null;
		switch (pc.id) {
			case "alipay":
				txt = "检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？";
				break;
			default:
				txt = "系统未安装“" + pc.description + "”服务，无法完成支付，是否立即安装？";
				break;
		}
		plus.nativeUI.confirm(txt, function(e) {
			if (e.index == 0) {
				pc.installService();
			}
		}, pc.description);
		return false;
	} else {
		return true;
	}
}
//订单控制器
function orderPay($scope, $http) {
	orderId = orders.orderId;
	var url = getUrl("60payList");
	var header = getHeader();
	//获取订单支持的支付方式
	$http({
		method: 'POST',
		url: url,
		timeout: 10000,
		headers: header,
		data: 'id=' + orderId
	}).success(function(data, status, headers, config) {

		if (data.code == 0) {
			var payList = data.obj.list;
			for (var i = 0; i < payList.length; i++) {
				var pays = payList[i];

				if (pays['code'] == 'weixinAPP') {
					setTimeout(function() {
						if (plus.os.name == "Android") {
							document.getElementById('wx').style.display = "block";
						}
					}, 200)

				}
				if (pays['code'] == 'alipay') {
					document.getElementById('ali').style.display = "block";
				}
				if (pays['code'] == 'offLine') {
					document.getElementById('offLine').style.display = "block";
				}
			}
		}
		if (data.code == 1 || data.code == 3 || data.code == 4) {
			mui.toast("支付方式获取失败，请稍后重试")
		}
		if (data.code == 2) {
			mui.toast('不支持线上支付')
		}
	}).error(function(date, status, headers, config) {
		mui.toast("支付方式获取失败，请稍后重试")
	})

	if (orders.shopName) {
		$scope.circleName = orders.shopName;
	} else {
		$scope.circleName = readData(localStorage.circleName);
	}
	//下列出现||运算符的都是因为后台返回字段名字不一样所以进行判断
	$scope.orderNo = orders.orderNumber;
	$scope.mon = orders.heji || orders.amount;
	$scope.num = orders.quantity;
	$scope.freight = orders.fee;
	$scope.bcPayAmount = orders.bcPayAmount || orders.shouldPay;
	allGoods = orders.list;
	for (var index = 0; index < allGoods.length; index++) {
		allGoods[index].speccolor = allGoods[index].speccolor || allGoods[index].specColorpr;
		allGoods[index].specsize = allGoods[index].specsize || allGoods[index].specSizepr;
		allGoods[index].specspec = allGoods[index].specspec || allGoods[index].specSpec;
		allGoods[index].specmodel = allGoods[index].specmodel || allGoods[index].specModel;
		allGoods[index].price = allGoods[index].price || allGoods[index].nowPrice
	}
	$scope.allGoods = allGoods;
	//微信支付操作
	wxPay = function() {
		var channel = payChannels["wxpay"]
		if (checkServices(channel)) {
			plus.nativeUI.showWaiting()
			var url = getUrl("56wxPay");
			var headerJson = getHeader();
			var jsons = 'orderId=' + orderId + '&payCode=weixinAPP'
			$http({
				method: 'POST',
				url: url,
				timeout: 10000,
				headers: headerJson,
				data: jsons
			}).success(function(data, status, headers, config) {
				testdata1 = {
					"retcode": 0,
					"retmsg": "ok",
					'appid': data.obj.appid,
					'partnerid': data.obj.partnerid,
					'prepayid': data.obj.prepayid,
					'package': data.obj.package,
					'noncestr': data.obj.noncestr,
					'timestamp': data.obj.timestamp,
					'sign': data.obj.sign
				}
				plus.payment.request(channel, testdata1, function() {
					delete localStorage.conformOrder;
					openOrderPaySuccess();
				}, function(e) {
					mui.toast(e.message)
				});
				plus.nativeUI.closeWaiting()
			}).error(function(date, status, headers, config) {
				mui.toast("网络异常请稍后重试");
				plus.nativeUI.closeWaiting()
			})
		}
	}

	offLinePay = function() {
		mui.toast("请去收银台支付找导购核销");
	}

	aliPay = function() {
		var channel = payChannels["alipay"];
		var urlAli = getUrl("58aliPay");
		var headerJsonAli = getHeader();
		var datas = 'orderId=' + orderId + '&payCode=alipay&aliPayType=11';
		if (checkServices(channel)) {
			$http({
				method: 'POST',
				url: urlAli,
				timeout: 10000,
				headers: headerJsonAli,
				data: datas
			}).success(function(data, status, headers, config) {
				if (data) {
					/*mui.openWindow({
						url: "orderPayAlipay.html",
						id: "orderPayAlipay.html",
						extras: {
							alipayret: data
						},
						waiting: {
							autoShow: false, //自动显示  等待框，默认为true
						}
					})*/					
					datas = data.obj;					
					var paydata ='service="' + datas.service +'"&partner="' + datas.partner + '"&seller_id="' + datas.seller_id + '"&_input_charset="'+datas._input_charset+'"&payment_type="'+datas.payment_type+'"&notify_url="' + datas.notify_url +'"&out_trade_no="' + datas.out_trade_no +'"&subject="' + datas.subject +'"&total_fee="' + datas.total_fee + '"&body="' + datas.body +'"&sign="'+datas.sign+ '"&sign_type="' + datas.sign_type+'"';
					plus.payment.request(channel, paydata, function(result) {
						delete localStorage.conformOrder;
						openOrderPaySuccess();
					}, function(e) {
						plus.nativeUI.toast("付款失败请重试")
							//plus.nativeUI.alert("更多错误信息请参考支付(Payment)规范文档：http://www.html5plus.org/#specification#/specification/Payment.html", null, "支付失败：" + e.code);
					});
				} else {
					mui.toast('支付失败')
				}
			}).error(function(date, status, headers, config) {
				mui.toast('支付失败1')
			})
		}
	}
}
//打开订单管理
function openOrder() {
	OpenNewWin({
		url: "orderManager.html",
		id: "orderManager.html"
	})
}

function closeWin() {
	var self = plus.webview.currentWebview();
	var conformorder = plus.webview.getWebviewById("conformOrder.html");
	if (conformorder) {
		conformorder.close();
	}
	delete localStorage.conformOrder;
	self.close();
}
window.addEventListener("closeWin", function() {
	closeWin();
})
mui.back = function() {
	closeWin();
}